映射数据结构


The ds_map data structure is an exceptionally useful one as it lets you store key and value pairs. For example, a character in your game can have a quantity of different items (keys) and for each individual item he can have a number of them (values), like in an RPG where you can have 10 health potions, 5 mana potions and 100 gold. 映射数据在一个地方将这些键值对保持在一起,你可以将键值对添加到映射中,并使用一些简单的函数搜索某些键对应的值。There are a couple of things you should know about maps before you use them, however!Maps are not sorted in any (recognisable) way, meaning that to find a certain key you may have to iterate through the whole thing (which is very slow). There is also no way to hold two keys that are the same, nor can you assign one key two values.

NOTE: The ds_map functions have changed since previous versions of GameMaker so imported games may not work or behave as you expect.
注意: 跟动态资源一样,数据结构会消耗内存,因此当不再使用它时应当销毁释放内存,以防止内存泄漏拖慢游戏运行效率甚至崩溃


The following functions exist that deal with DS maps.

  1. ds_map_exists
  2. ds_map_create
  3. ds_map_add
  4. ds_map_clear
  5. ds_map_copy
  6. ds_map_replace
  7. ds_map_delete
  8. ds_map_empty
  9. ds_map_size
  10. ds_map_find_first
  11. ds_map_find_last
  12. ds_map_find_next
  13. ds_map_find_previous
  14. ds_map_find_value
  15. ds_map_set
  16. ds_map_read
  17. ds_map_write
  18. ds_map_destroy

There are four further functions available for saving and loading a ds_map. These functions will obfuscate the map and store it in a secure location on the target platform using a file format that means that the final file is not able to be transfered between devices:

  1. ds_map_secure_save
  2. ds_map_secure_save_buffer
  3. ds_map_secure_load
  4. ds_map_secure_load_buffer

Apart from these specific functions you can all use an expression (called an accessor) to add or modify the contents of your ds_map. 访问器看起来就像一维数组,语法如下

map_index[?key]

你还可以找到更多相关内容,比如你可以在GML总览页查看更多关于 Accessors的介绍.


JSON And DS Maps

One of the uses that ds_maps have is when working with JSON, and so there are a few special functions that are specific to that:

  1. ds_map_add_list
  2. ds_map_add_map
  3. ds_map_replace_list
  4. ds_map_replace_map

There are also a couple of complimentary functions for ds_lists:

  1. ds_list_mark_as_list
  2. ds_list_mark_as_map
NOTE: While these functions permit you to add lists and maps within a map, they are useless for anything other than JSON, and nested maps and lists will not be read correctly if written to disk or accessed in any other way.
注意:如果你需要检查数据结构是否存在,你可以使用ds_exists()函数。